package com.kfh.ybracelet.db;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.kfh.ybracelet.bean.MessageBean;
import com.kfh.ybracelet.utils.Constant;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 数据库操作类
 * Created by Aaron on 15/12/15.
 */
public class DatabaseManager {

    private SharedPreferences sp;

    private DatabaseManager() {
    }

    private static DatabaseManager dbManager = new DatabaseManager();

    public static DatabaseManager getInstance() {
        return dbManager;
    }

    private SQLiteDatabase db;
    private DatabaseHelper dbHelper;

    /**
     * 初始化打开数据库
     *
     * @param ctx
     * @return
     */
    public void initDb(Context ctx) {

        if (dbHelper == null)
            dbHelper = new DatabaseHelper(ctx);

        sp = ctx.getSharedPreferences(Constant.CONFIG, Context.MODE_PRIVATE);

        db = dbHelper.getWritableDatabase();

    }

    public SQLiteDatabase getDb() {
        return db;
    }

    /**
     * 往历史记录表里面插入数据
     *
     * @param args 插入的数据集合
     */
    public synchronized void insertHisData(Context ctx, Object[] args) {

        initDb(ctx);

        if (isOpen())
            db.execSQL("insert into " + Constant.HISTORY_TABLE + " (sendId, sendName, sendPic, receiverTime, isRead, content, topic, " +
                    "messageType, receiveId, receiveName, receivePic, voiceLength, chatType, sendTime, userId, isListener) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", args);

        closeDataBase();
    }

    /**
     * 根据topic,sendDate,sendId 查询数据库里是否有该条消息
     *
     * @param topic
     * @param sendDate
     * @return true 有接受过该消息  false 没有接受过该消息
     */
    public synchronized boolean hasReceived(Context ctx, String topic, long sendDate, String sendId, String userId) {

//        Log.e("tag", "topic:" + topic + ",sendDate:" + sendDate + ",sendId:" + sendId + ",userId:" + userId);

        initDb(ctx);

//        Cursor cursor = db.rawQuery("select * from " + Constant.HISTORY_TABLE + " where topic=? and sendTime=? and sendId=? and userId=?",
        Cursor cursor = db.rawQuery("select * from " + Constant.HISTORY_TABLE + " where topic=? and sendTime=? and sendId=? and userId=? order by _id desc limit 200",
                new String[]{topic, sendDate + "", sendId, userId});

        Log.e("tag", " 查询出来的消息个数 : " + cursor.getCount());
//        if (cursor.getCount() > 0) {
//            cursor.close();
//            closeDataBase();
//            return true;
//        } else {
//            cursor.close();
//            closeDataBase();
//            return false;
//        }

        boolean hasReceived = (cursor.getCount() > 0);
        cursor.close();
        closeDataBase();
        return hasReceived;

    }


    /**
     * 查询历史聊天记录
     * 从from条 到 end条的数据 (根据topic查询)
     *
     * @param topic  sendId, sendName, sendPic," +
     *               "receiverTime, isRead, content, topic, messageType" +
     *               ", receiveId, receiveName, receivePic, voiceLength, chatType, sendTime
     * @param from   从多少开始
     * @param userId 当前登录的用户的id
     */
    public synchronized List<MessageBean> queryChatHistory(Context ctx, String userId, String topic, int from) {

        initDb(ctx);

        List<MessageBean> mbList = new ArrayList<>();

        if (isOpen()) {

            //查询该topic的倒叙 从 from 到 end 的聊天记录
            try {

                Cursor cursor = db.rawQuery("select * from " + Constant.HISTORY_TABLE + " where topic=? and userId=? order by sendTime desc limit ?,?",
                        new String[]{topic, userId, from + "", Constant.CHAT_HISTORY_COUNT + ""});//得到游标

                while (cursor.moveToNext()) {

                    MessageBean mb = new MessageBean();
                    mb.id = cursor.getString(0);
                    mb.sendId = cursor.getString(1);
                    mb.sendName = cursor.getString(2);
                    mb.sendPic = cursor.getString(3);
                    mb.content = cursor.getString(6);
                    mb.messageType = cursor.getString(8);
                    mb.receiveId = cursor.getString(9);
                    mb.receiveName = cursor.getString(10);
                    mb.receivePic = cursor.getString(11);
                    mb.voiceLength = cursor.getDouble(12);
                    mb.chatType = cursor.getInt(13);
                    mb.sendDate = cursor.getLong(14);
                    mb.isListener = cursor.getInt(16);
                    mb.channelId = topic;

                    mbList.add(mb);

                }

                cursor.close();
                Collections.reverse(mbList);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        closeDataBase();

        return mbList;
    }

    /**
     * 获取topic表里面的所有聊天记录,即最近的聊天列表
     */
    public synchronized List<MessageBean> getChatListFromTopics(Context ctx, String userId) throws Exception {

//        if (Constant.topicMap == null) {
//            SharedPreferences sp = ctx.getSharedPreferences(Constant.CONFIG, Context.MODE_PRIVATE);
//            Constant.topicMap = (Map<String, TopicBean>) JSON.parse(sp.getString(Constant.TOPIC_MAP, ""));
//        }
//
//        Set<String> topicSet = Constant.topicMap.keySet();
//
//        Iterator<String> iterator = topicSet.iterator();
//        String conduction = "";
//        while (iterator.hasNext()) {
//            conduction = conduction + "'" + iterator.next() + "',";
//        }
//
//        String substring = conduction.substring(0, conduction.length() - 1);
//
//        Log.e("tag", " topic 合集 : " + substring);
        initDb(ctx);

        List<MessageBean> mbs = new ArrayList<>();

        if (db != null && db.isOpen()) {
//            Cursor cursor = db.rawQuery("select * from " + Constant.TOPIC_TABLE + " order by _id desc ", null);//得到游标
            createTable(db);
            Cursor cursor = db.rawQuery("select * from " + Constant.TOPIC_TABLE + sp.getString(Constant.USERID, "") + " where userId=? order by sendTime desc ", new String[]{userId});//得到游标
//            Cursor cursor = db.rawQuery("select * from " + Constant.TOPIC_TABLE + " where topic in ?", new String[]{"(" + substring + ")"});//得到游标

            while (cursor.moveToNext()) {

                if (cursor.getString(2) != null && cursor.getString(2).startsWith(Constant.START_SYSTEM)) {//如果是系统topic则不存储,继续查询
                    continue;
                }

                add2topic(mbs, cursor);
            }

            cursor.close();
            cursor = null;
        }

        closeDataBase();

        return mbs;

    }

    private void add2topic(List<MessageBean> mbs, Cursor cursor) {
        MessageBean msb = new MessageBean();

        msb.receiveName = cursor.getString(1);
        msb.channelId = cursor.getString(2);
        msb.sendId = cursor.getString(3);
        msb.sendName = cursor.getString(4);
        msb.sendPic = cursor.getString(5);
        msb.receiverTime = cursor.getString(6);
        msb.receiveId = cursor.getString(7);
        msb.content = cursor.getString(8);
        msb.messageType = cursor.getString(9);
        msb.voiceLength = cursor.getDouble(10);
        msb.chatType = cursor.getInt(11);
        msb.sendDate = cursor.getLong(12);
        msb.receivePic = cursor.getString(13);
        msb.receiveName = cursor.getString(14);
        msb.isRead = cursor.getInt(15);
        msb.isListener = cursor.getInt(17);

//        LogUtil.e("tag", "  未读个数 : " + msb.isRead);

        mbs.add(msb);
    }

    /**
     * 清空历史记录
     */
    public synchronized void deleteHistory(Context ctx, String topic, String userId) {

        initDb(ctx);

        if (isOpen()) {
            db.execSQL("delete from " + Constant.HISTORY_TABLE + " where topic=? and userId=?", new Object[]{topic, userId});
        }

        closeDataBase();
    }

    /**
     * 删除最近聊天的表中的 某个topic的记录
     *
     * @param topic 聊天的topic
     */
    public synchronized void deleteTopic(Context ctx, String topic, String userId) {

        initDb(ctx);

        if (isOpen()) {
            createTable(db);
            db.execSQL("delete from " + Constant.TOPIC_TABLE + sp.getString(Constant.USERID, "") + " where topic=? and userId=?", new Object[]{topic, userId});
        }

        closeDataBase();
    }


    /**
     * 把语音设置为已读(历史记录表)
     *
     * @param args
     */
    public synchronized void updateListenerStatus(Context ctx, String[] args) {

        initDb(ctx);

        if (isOpen()) {
            db.execSQL("update " + Constant.HISTORY_TABLE + " set isListener=? where topic=? and userId=? and sendId=? and sendTime=?", args);
        }

        closeDataBase();

    }

    /**
     * 把语音设置为已读(topic表)
     *
     * @param args
     */
    public synchronized void updateTopicListenerStatus(Context ctx, String[] args) {

        initDb(ctx);

        if (isOpen()) {
            createTable(db);
            db.execSQL("update " + Constant.TOPIC_TABLE + sp.getString(Constant.USERID, "") + " set isListener=? where topic=? and userId=? and sendId=? and sendTime=?", args);
        }

        closeDataBase();
    }


    /**
     * 清空单人聊天消息
     *
     * @param
     */
    public synchronized void clearTopic(Context ctx, String[] args) {

        initDb(ctx);

        if (isOpen()) {
            createTable(db);
            db.execSQL("update " + Constant.TOPIC_TABLE + sp.getString(Constant.USERID, "") + " set sendId=?,content=?" +
                    ",messageType=?,chatType=?,receivePic=?, receiveName=?,receiveId=? where topic=? and userId=?", args);
        }

        closeDataBase();
    }

    /**
     * 更新数据库 红点个数
     *
     * @param args
     */
    public synchronized void clearRedCount(Context ctx, String[] args) {

        initDb(ctx);

        if (isOpen()) {
            createTable(db);
            db.execSQL("update " + Constant.TOPIC_TABLE + sp.getString(Constant.USERID, "") + " set isRead=? where topic=? and userId=?", args);

        }
        closeDataBase();
    }

    /**
     * 更新topic表数据
     * topicName 为群的名称
     *
     * @param args 需要修改的参数
     */
    public synchronized int updateTopic(Context ctx, String[] args) {

        initDb(ctx);

        int count = 0;
        long sendTime = 0; //上条消息的sendTime

        Cursor cursor = queryUnreadCount(new String[]{args[15], args[16]});

        if (cursor.getCount() > 0) {

            while (cursor.moveToNext()) {

                sendTime = cursor.getLong(12);
                count = cursor.getInt(15);

            }
            cursor.close();

        }

        if (sendTime > Long.parseLong(args[10])) {
            //如果上条消息的sendTime 大于 当前接受的 则当前的消息不存储,只把未读消息+1 (防止离线消息错乱)

            createTable(db);
            String[] strings = {++count + "", args[15], args[16]};
            db.execSQL("update " + Constant.TOPIC_TABLE + sp.getString(Constant.USERID, "") + " set isRead=? where topic=? and userId=?", strings);
            closeDataBase();
            return count;
        }

        if (count < 1) {
            //topic表中没有该调记录
//            LogUtil.e("tag", " 数据库中无该条记录, 插入新topic ");
            createTable(db);
            db.execSQL("replace into " + Constant.TOPIC_TABLE + sp.getString(Constant.USERID, "") + "(topicName, sendId, sendName, sendPic, receiverTime, receiveId" +
                    ",content, messageType, voiceLength, chatType, sendTime, receivePic, receiveName, isListener, isRead, topic, userId) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", args);

            count = 1;

        } else {

            //topic表中有记录, 更新数据
//            LogUtil.e("tag", " 数据库中有记录,查出未读条数   ");

            args[14] = ++count + "";
            createTable(db);
            db.execSQL("update " + Constant.TOPIC_TABLE + sp.getString(Constant.USERID, "") + " set topicName=?, sendId=?, sendName=?, sendPic=?, receiverTime=?" +
                    ", receiveId=?, content=?, messageType=?, voiceLength=?, chatType=?, sendTime=?, receivePic=?" +
                    ", receiveName=?, isListener=?, isRead=? where topic=? and userId=?", args);

        }

        closeDataBase();

        return count;

    }

    private synchronized Cursor queryUnreadCount(String[] args) {

        createTable(db);
        return db.rawQuery("select * from " + Constant.TOPIC_TABLE + sp.getString(Constant.USERID, "") + " where topic=? and userId=?", args);//得到游标

//        int count = 0;
//        if (cursor.getCount() > 0) {
//
//            while (cursor.moveToNext()) {
//
//                long sendTime = cursor.getLong(12);
//                count = cursor.getInt(15);
//
//            }
//            cursor.close();
//
//        }
//
//        return cursor;
    }

    /**
     * 更新topic表数据
     * topicName 为群的名称
     *
     * @param args 需要修改的参数
     */
    public synchronized int updateTopicWithoutInfo(Context ctx, String[] args) {

        initDb(ctx);

        int count = 0;
        Cursor cursor = queryUnreadCount(new String[]{args[10], args[11]});

        if (cursor.getCount() > 0) {

            while (cursor.moveToNext()) {

                count = cursor.getInt(15);

            }
            cursor.close();

        }

        if (count < 1) {
            //topic表中没有该调记录

            count = 1;

        } else {

            args[9] = ++count + "";
            createTable(db);
            db.execSQL("update " + Constant.TOPIC_TABLE + sp.getString(Constant.USERID, "") + " set sendId=?, sendName=?, sendPic=?, receiverTime=?, content=?" +
                    ", messageType=?, voiceLength=?, chatType=?, sendTime=?, isRead=? where topic=? and userId=?", args);
        }

        closeDataBase();

        return count;

    }

    /**
     * 查询所有的未读消息个数
     *
     * @return
     */
    public synchronized int queryAllUnReadCount(Context ctx, String userId) {

        initDb(ctx);

        int sum = 0;
        createTable(db);
        Cursor cursor = db.rawQuery("select sum(isRead) from " + Constant.TOPIC_TABLE + sp.getString(Constant.USERID, "") + " where userId=?", new String[]{userId});

        while (cursor.moveToNext()) {
            sum = cursor.getInt(0);
        }

        cursor.close();

        closeDataBase();

        return sum;
    }

    /**
     * 关闭db
     */
    private void closeDataBase() {

        if (isOpen()) {
            db.close();
            db = null;
        }

    }

    /**
     * 数据库是否是打开的状态
     *
     * @return true 打开, false 关闭状态
     */
    public boolean isOpen() {

        return db != null && db.isOpen();

    }

    /**
     * 如果topic表不存在 则创建topic表
     *
     * @param db
     */
    public void createTable(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE IF NOT EXISTS " + Constant.TOPIC_TABLE + sp.getString(Constant.USERID, "") +
                " (_id INTEGER , topicName VARCHAR, topic VARCHAR, sendId VARCHAR, " +
                "sendName VARCHAR, sendPic VARCHAR," + "receiverTime VARCHAR, receiveId VARCHAR, content VARCHAR," +
                " messageType VARCHAR, voiceLength VARCHAR, chatType VARCHAR, sendTime VARCHAR, receivePic VARCHAR, " +
                "receiveName VARCHAR, isRead INTEGER, userId VARCHAR, isListener VARCHAR, PRIMARY KEY(topic))");
    }

}
